package com.code.coinprice.handlers;

import com.code.coinprice.consts.CommonConstant;
import com.code.coinprice.managers.CoinPriceManager;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
import io.netty.util.AttributeKey;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 如果不添加可采用前端轮询的方式定时向服务端发送数据。
 * HearBeatHandler 对websocket进行心跳监测（websocket默认长时间无通信会自动关闭通道，通常做法可以前端轮询向服务端发送消息，也可以后端服务器自己进行心跳监控，定时发送信息保持连接状态）
 */
public class HearBeatHandler extends ChannelInboundHandlerAdapter {

    private static final Logger log = LoggerFactory.getLogger(HearBeatHandler.class);

    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) {
        if (evt instanceof IdleStateEvent) {
            IdleStateEvent idleStateEvent = (IdleStateEvent) evt;
            AttributeKey<String> key = AttributeKey.valueOf(CommonConstant.CLIENT_CHANNEL_ID);
            String clientChannelId = ctx.channel().attr(key).get();
            String checkOff = CoinPriceManager.heartBeatMap.get(CommonConstant.HEART_CHECK_OFF);
            if (idleStateEvent.state() == IdleState.READER_IDLE) {
                log.info("读空闲事件触发...clientChannelId:{}", clientChannelId);
                if ("0".equals(checkOff)) {
                    ctx.channel().writeAndFlush(new TextWebSocketFrame(""));
                }
            } else if (idleStateEvent.state() == IdleState.WRITER_IDLE) {
                log.info("写空闲事件触发...clientChannelId:{}", clientChannelId);
                if ("0".equals(checkOff)) {
                    ctx.channel().writeAndFlush(new TextWebSocketFrame(""));
                }
            } else if (idleStateEvent.state() == IdleState.ALL_IDLE) {
                log.info("读写空闲事件触发 clientChannelId:{}", clientChannelId);
                if ("0".equals(checkOff)) {
                    ctx.channel().writeAndFlush(new TextWebSocketFrame(""));
                }
                //System.out.println("关闭通道资源");
                //ctx.channel().close();
            }
        }
    }

}
